package org.deyang.tools.amazon;

import java.io.IOException;
import java.util.Iterator;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.deyang.tools.amazon.exceptions.KeepaContentException;
import org.deyang.tools.amazon.pricetracker.KeepaPriceAnalyzer;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;

public class EnqueueProductIntoQueueServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2511142216188244896L;
	private static final Logger log = Logger.getLogger(EnqueueProductIntoQueueServlet.class.getName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		String asin = req.getParameter("asin");
		String operation = req.getParameter("operation");
		if (asin != null && !asin.equals("")){
			Query asinq = new Query("AmazonProduct");
			asinq.addFilter("asin", Query.FilterOperator.EQUAL, asin);
			DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
			Iterator<Entity> iter = datastore.prepare(asinq).asIterator();
			Entity twitterEntry;
			if (iter.hasNext()){
				log.info("The select product is already in db - update information");
				twitterEntry = iter.next();
				//twitterEntry.setProperty("isPendingToTwitter", true);
				twitterEntry.setProperty("dealPrice", req.getParameter("saleprice"));
				twitterEntry.setProperty("dealRate", req.getParameter("dealrate"));
			    twitterEntry.setProperty("twitterSaleText", req.getParameter("saletext"));
			    twitterEntry.setProperty("amazonProductTitle", req.getParameter("twitterproductdesc"));
			    twitterEntry.setProperty("trackStatus", "T");
			    //twitterEntry.setProperty("isDealForNotify", false);
			    twitterEntry.setProperty("shorturl", req.getParameter("shorturl"));
			    twitterEntry.setProperty("imgurl", req.getParameter("imgurl"));
			}else{
				log.info("Create the entity for selected product");

				twitterEntry = new Entity("AmazonProduct");
				twitterEntry.setProperty("asin", asin);
			    //twitterEntry.setProperty("isPendingToTwitter", true);
			    twitterEntry.setProperty("dealPrice", req.getParameter("saleprice"));
				try {
					KeepaPriceAnalyzer kpa = new KeepaPriceAnalyzer(asin);
					twitterEntry.setProperty("PriceHistoryData",new Text(kpa.getAmazonPriceHistoryStr()));
				} catch (KeepaContentException e) {
					log.warning(e.getMessage());
					e.printStackTrace();
				}
			    twitterEntry.setProperty("dealRate", req.getParameter("dealrate"));
			    twitterEntry.setProperty("twitterSaleText", req.getParameter("saletext"));
			    twitterEntry.setProperty("amazonProductTitle", req.getParameter("twitterproductdesc"));
			    twitterEntry.setProperty("trackStatus", "T");
			    //twitterEntry.setProperty("isDealForNotify", false);
			    twitterEntry.setProperty("shorturl", req.getParameter("shorturl"));
			    twitterEntry.setProperty("imgurl", req.getParameter("imgurl"));
			}
			datastore.put(twitterEntry);
			
			if (operation == null || !operation.equals("track")){
				Queue queue = QueueFactory.getQueue("twitterpostqueue");
			    queue.add(TaskOptions.Builder.withUrl("/twitterpost").param("key", KeyFactory.keyToString(twitterEntry.getKey())));	
			}
			
		    Queue trackQueue = QueueFactory.getQueue("trackproductqueue");
		    trackQueue.add(TaskOptions.Builder.withUrl("/addtracklist").param("asin", asin).param("trackStatus", "T"));
		    
		}
	}

}
